package main

import (
	host_manager "awesome_host/host"
	"flag"
	"fmt"
	"log"
	"math/rand"
	"os"
	"strings"
	"time"
)


type Param struct {
	GlobalFind bool
}

var param Param

func init() {
	//log.SetPrefix("awesome_host ")
	log.SetFlags(log.Ldate | log.Ltime )

	flag.BoolVar(&param.GlobalFind, "global_find", false,
		"find available nodes both at home and abroad, default is querying aboard only.")

}

func AwesomeHost(host, linetype string) (*Node, error) {
	nodes, err := QueryAvailableNodes(host, linetype)
	if err != nil {
		return nil, err
	}

	rand.Seed(time.Now().Unix())
	availableNode := nodes[rand.Intn(len(nodes)-1)]
	log.Printf("avaliable host: %+v\n", availableNode)

	hostsFile :=  ""
	hostsFile = host_manager.GetHostFile()
	if err = BackupFile(hostsFile);err != nil {
		return nil, fmt.Errorf("backup host error:%v",err)
	}

	tmpFileName, err := AddHost2TmpFile(hostsFile, host, availableNode.pingRsp.ip)
	if err != nil {
		return nil, fmt.Errorf("write host to tmp file err:%v", err)
	}
	_, err = CopyFile(tmpFileName, hostsFile)
	if err != nil {
		return availableNode, fmt.Errorf("write host error, you need check your host whether is ok!!! error:%v", err)
	}
	os.Remove(tmpFileName)
	return availableNode, nil
}

func print(node *Node, err error) {
	fmt.Println(strings.Repeat("*", 30))
	if err != nil {
		fmt.Printf("!!!error!!! please check your hosts is ok...\n")
	} else {
		fmt.Printf("available host: %s, %s, rtt:%v\n", node.pingRsp.ip, node.pingRsp.ipaddress, node.localPingRtt)
	}
	fmt.Println(strings.Repeat("*", 30))
}

func pause() {
	var s string
	fmt.Scan(&s)
}

//go build -ldflags="-w -s"
//upx.exe -9 awesome_host.exe
func main() {
	flag.Parse()

	host := "github.com"
	regions := "海外"
	if param.GlobalFind {
		regions = ""
	}
	print(AwesomeHost(host, regions))

	fmt.Println("Finished.Press any key to continue...")
	pause()
}
